/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "AppVersion.h"
#include <bundle/native_interface_bundle.h>
#include "Application.h"

REGISTER_PLUGIN_CLASS(AppVersion)
bool AppVersion::execute(const string&  action, cJSON* args, CallbackContext cbc)
{
    if(action == "onArKTsResult") {
        return onArKTsResult(args);
    }
    
    if(action == "getAppName") {
        m_cbc = cbc;
        if(m_strAppName.empty()) {
            executeArkTs("/pages/getAppName", 0, "getAppName", "AppVersion", cbc);
        } else {
            cbc.success(m_strAppName);
        }
    }
    
    if(action == "getPackageName") {
        OH_NativeBundle_ApplicationInfo application = OH_NativeBundle_GetCurrentApplicationInfo();
        cbc.success(application.bundleName);
    }
    
    if(action == "getVersionNumber") {
        m_cbc = cbc;
        if(m_strVersionNumber.empty()) {
            executeArkTs("/pages/getAppName", 0, "getVersionNumber", "AppVersion", cbc);
        } else {
            cbc.success(m_strVersionNumber);
        }
    }
    
    if(action == "getVersionCode") {
        m_cbc = cbc;
        if(m_lngVersionCode == 0) {
            executeArkTs("/pages/getAppName", 0, "getVersionCode", "AppVersion", cbc);
        } else {
            cbc.success(m_lngVersionCode);
        }
    }
    
    return true;
}

bool AppVersion::onArKTsResult(cJSON* args)
{
    string content = cJSON_GetObjectItem(args, "content")->valuestring;
    cJSON* json = cJSON_GetObjectItem(args, "result");
    if(json != NULL && json->type == cJSON_Array) {
        int count = cJSON_GetArraySize(json);
        if(count > 0) {
            m_strAppName = cJSON_GetArrayItem(json, 0)->valuestring;
        } 
        
        if(count > 1) {
            m_strVersionNumber = cJSON_GetArrayItem(json, 1)->valuestring;
        } 
        
        if(count > 2) {
            m_lngVersionCode = atol(cJSON_GetArrayItem(json, 2)->valuestring);
        } 
    }
    
    if(content == "getAppName") {
         m_cbc.success(m_strAppName);
    }
    
    if(content == "getVersionNumber") {
         m_cbc.success(m_strVersionNumber);
    }
    
    if(content == "getVersionCode") {
         m_cbc.success(m_lngVersionCode);
    }
    
    return true;
}